//获取极光IM签名
function getIMSignature(){
  var signatureStr = _GetPrefs('JIMSignature');
  console.log("last_signature:" + signatureStr)
  if(signatureStr != ''){
    var signature = JSON.parse(signatureStr)
    var timestamp = new Date().getTime()//当前时间的毫秒值
    console.log("now timestamp:" + timestamp);
    console.log("last timestamp:" + signature.timestamp);
    console.log("duration timestamp:" + (timestamp - signature.timestamp));
    if (timestamp - signature.timestamp < 10 * 60 * 1000) {//签名10 分钟内有效
      return signature;
    }
  }
  var appkey = "027dc6f0202fc7eda140bcaf";
  var master_secret = "115243879a74e48f3ca8650d";
  var random_str = randomString();
  var timestamp = new Date().getTime();
  var str = "appkey=" + appkey + "&timestamp=" + timestamp + "&random_str=" + random_str + "&key=" + master_secret;
  var signature = md5(str);
  var data = {
    "appkey":appkey,
    "random_str":random_str,
    "signature":signature,
    "timestamp":timestamp,
    "flag" : 0
  }
  _SetPrefs('JIMSignature', data);
  return data;
}

//创建极光IM实例
function NewJIM() {
  console.log("【new JIM】");
  window.JIM = new JMessage({
    debug: true
  });
}

//异常断线监听
function OnDisconnectJIM() {
  JIM.onDisconnect(function () {
    console.log("【JIM onDisconnect】");
    // store.commit('updateSignatureInfo', null)
    NewJIM()
  });
}
//初始化状态
function IsJIMInit() {
  console.log('【JIM isInit】:' + JIM.isInit());
  return JIM.isInit();
}

//登录状态
function IsJIMLogin() {
  console.log('【JIM isLogin】:' + JIM.isLogin());
  return JIM.isLogin();
}

//初始化
function InitJIM(username){
  if(typeof(JIM) =="undefined"){
      NewJIM();
      OnDisconnectJIM();
  }
  if(IsJIMInit())
  {
    console.log('JIM is already init')
    LoginJIM(username);
  }else {
    var signature = getIMSignature();
    console.log("【InitJIM】" + JSON.stringify(signature))
    JIM.init(signature).onSuccess(function(data) {
      console.log(JSON.stringify(data));
       //data.code 返回码
       //data.message 描述
       LoginJIM(username);
      }).onFail(function(data) {
        console.log(JSON.stringify(data));
        // 同上
    });
  }
}

//刷新红点
function updateUnreadStatus(){
  JIM.getConversation().onSuccess(function(ret) {//会话列表
    console.log('getConversation:' + JSON.stringify(ret))
    var conversations = ret.conversations;
    var existUnread = false;
    for(var i = 0; i < conversations.length;i++){
      var conversation = conversations[i];
      if(conversation.unread_msg_count > 0){
        existUnread = true;
      }
    }
    var redPoint = $("#redPoint")
    if(existUnread && redPoint){
        $("#redPoint").show();
    }else{
        $("#redPoint").hide();
    }
  });
}
//登录
function LoginJIM(username){
  if (IsJIMLogin()) {
    console.log('JIM already login');
    return;
  }
  console.log("【LoginJIM】" + username)
  JIM.login({
      'username' : username,
      'password' : 'quanbao123'
  }).onSuccess(function(data) {
    console.log("loginJIM:" + JSON.stringify(data))
    updateUnreadStatus();
    JIM.onMsgReceive(function(data) {//聊天消息实时监听
      console.log("JIM.onMsgReceive:" + JSON.stringify(data))
      updateUnreadStatus();
      var messages = _GetPrefs('JIMessages');
      if(messages == ''){
        _SetPrefs('JIMessages', data.messages);
      }else{
        var msgList = JSON.parse(messages)
        data.messages.forEach(function(element) {
          msgList.push(element);
        });
        _SetPrefs('JIMessages', msgList);
      }
    });
    JIM.onSyncConversation(function(data) {//离线消息同步监听
      console.log("JIM.onSyncConversation:" + JSON.stringify(data))
      var messages = _GetPrefs('JIMessages');
      if(messages == ''){
        _SetPrefs('JIMessages', data[0].msgs);
      }else{
        var msgList = JSON.parse(messages)
        data[0].msgs.forEach(function(element) {
          var exist = false;
          for(var i = 0; i < msgList.length; i++){
            if(msgList[i].msg_id == element.msg_id){
              exist = true
            }
          }
          if(!exist){
            msgList.push(element);
          }
        });
        _SetPrefs('JIMessages', msgList);
      }
    });
    JIM.onEventNotification(function (data) {//业务事件监听
      console.log('event_receive: ' + JSON.stringify(data));
    });
    JIM.onUserInfUpdate(function (data) {//用户信息变更监听
      console.log('onUserInfUpdate : ' + JSON.stringify(data));
    });
    JIM.onSyncEvent(function (data) {//业务事件同步监听
      console.log('onSyncEvent : ' + JSON.stringify(data));
    });
    JIM.onMsgReceiptChange(function (data) {//消息已读数变更事件实时监听
      console.log('onMsgReceiptChange : ' + JSON.stringify(data));
    });
    JIM.onSyncMsgReceipt(function (data) {//消息已读数变更事件同步监听
      console.log('onSyncMsgReceipt : ' + JSON.stringify(data));
    });
    JIM.onMutiUnreadMsgUpdate(function (data) {//会话未读数变更监听（多端在线）
      console.log('onConversationUpdate : ' + JSON.stringify(data));
    });
    JIM.onTransMsgRec(function (data) {//消息透传监听
      console.log('onTransMsgRec : ' + JSON.stringify(data));
    });
    JIM.onRoomMsg(function (data) {//聊天室消息监听
      console.log('onRoomMsg  : ' + JSON.stringify(data));
    });
  }).onFail(function(data){
    console.log(JSON.stringify(data))
    //同上
  });
}

//重置会话未读数
function resetMsgUnreadCount() {
  if(typeof(JIM) != 'undefined'){
    if(IsJIMLogin()){
      JIM.getConversation().onSuccess(function(ret) {//会话列表
        var conversations = ret.conversations;
        for(var i = 0; i < conversations.length;i++){
          var conversation = conversations[i];
          if(conversation.unread_msg_count > 0){
            if(conversation.type == 4){
              resetGroupMsgUnreadCount(conversation.gid);
            }else if(conversation.type == 3){
              resetSingleMsgUnreadCount(conversation.username);
            }
          }
        }
        var redPoint = $("#redPoint")
        if(redPoint){
            $("#redPoint").hide();
        }
      });
    }
  }
}

//获取会话未读数
function getUnreadMsgCnt(username) {
  var count = JIM.getUnreadMsgCnt({
    'username': username
  });
  console.log('getUnreadMsgCnt:' + count);
}

//重置单聊会话未读数
function resetSingleMsgUnreadCount(username) {
  console.log('resetUnreadCount:' + username)
  // 重置单聊会话，调用则成功，无回调函数
  JIM.resetUnreadCount({
    'username': username
  });
}

//重置群聊会话未读数
function resetGroupMsgUnreadCount(gid) {
  // 重置单聊会话，调用则成功，无回调函数
  console.log('resetUnreadCount:' + gid)
  JIM.resetUnreadCount({
    'gid': gid
  });
}
